<template>
  <a-modal
    :title="'编辑人群包'"
    :visible="true"
    width="50%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card>
        <a-row
          type="flex"
          justify="start"
          align="top"
        >
          <a-col :span="24">
            <a-form
              :form="form"
              @submit="handleSubmit"
              :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol"
            >
              <a-form-item
                label="人群包名称"
                :required="true"
              >
                <a-input
                  allow-clear
                  placeholder="请输入人群包名称"
                  :maxLength="40"
                  v-decorator="[
                  `groupName`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入人群包名称'
                      }
                    ]
                  }
                ]"
                />
              </a-form-item>

              <a-form-item
                label="顺序"
                :required="true"
              >
                <a-input-number
                  allow-clear
                  :min="1"
                  :max="999"
                  placeholder="请输入人群包顺序"
                  v-decorator="[
                  `distributeOrder`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        message: '请输入人群包顺序'
                      }
                    ]
                  }
                ]"
                />
              </a-form-item>
              <a-form-item
                label="销售区域"
              >
                <a-select
                  allow-clear
                  show-search
                  mode="multiple"
                  placeholder="请选择销售区域"
                  optionFilterProp="children"
                  @change="select"
                  v-model="salesAreaList"
                >
                  <a-select-option :value="selectAll">
                    全部
                  </a-select-option>
                  <a-select-option
                    :value="item.id"
                    v-for="(item,index) in areaList"
                    :key="index"
                  >
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="达摩标签ID(tagItemId)">
                <div
                  v-for="(item, index) in fileds"
                  :key="index"
                >
                  <a-row :gutter="16">
                    <a-col :span="8">
                      <a-select
                        allow-clear
                        show-search
                        placeholder="请选择品牌"
                        v-decorator="[
                  `names[${index}][name]`,
                  {
                    validateTrigger: ['change', 'blur'],
                  initialValue: item['name']
                  }
                ]"
                      >
                        <a-select-option
                          :value="item.name"
                          v-for="(item,index) in brandList"
                          :key="index"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>

                    </a-col>
                    <a-col :span="16">
                      <a-input
                        allow-clear
                        placeholder="请输入达摩标签ID"
                        v-decorator="[
                  `names[${index}][tagItemId]`,
                  {
                    validateTrigger: ['change', 'blur'],
                   initialValue: item['tagItemId']
                  }
                ]"
                      />
                    </a-col>
                    <a-icon
                      v-if="index == 0"
                      class="dynamic-delete-button mt-10"
                      type="plus-circle"
                      @click="add"
                    />
                    <a-icon
                      v-else
                      class="dynamic-delete-button mt-10"
                      type="minus-circle-o"
                      @click="() => remove(index)"
                    />

                  </a-row>
                </div>
              </a-form-item>
              <a-row style="margin-top:10px">
                <a-col
                  :span="8"
                  :offset="4"
                >
                  <div
                    @click="reset"
                    class="reset"
                  >
                    取消
                  </div>

                </a-col>
                <a-col :span="8">
                  <div
                    class="submit"
                    @click="handleSubmit"
                  >
                    提交
                  </div>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { bagListUpdate, areaList, getBrandList } from '@api/label/index'
const chanelList = [
  {
    value: 'member',
    name: '会员部'
  },
  {
    value: 'pos',
    name: 'POS+'
  },
  {
    value: 'integral',
    name: '积分商城'
  }
]
export default {
  components: {},

  props: {
    bag: {
      type: Object,
      default: null
    }
  },

  data() {
    return {
      chanelList,
      urlKey: 'account',
      id: '',
      patt: 'api/gateway/basemgt-op/',
      loading: true,
      form: this.$form.createForm(this),
      showOrder: true,
      areaList: [],
      allAreaId: [],
      brandList: [],
      salesArea: [],
      selectAll: 10000,
      ifAll: false,
      fileds: [],
      salesAreaList: [],
      distributeChannel: '',
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 18 },
          xs: { span: 16 },
          sm: { span: 16 }
        }
      }
    }
  },

  created() {
    const { bag } = this.$props
    console.log(bag.disItemList)
    const newArr = []
    if (bag.disItemList.length > 0) {
      bag.disItemList.map(item => {
        const obj = {
          name: item.name,
          tagItemId: item.tagItemId
        }
        newArr.push(obj)
      })
      this.fileds = newArr
    } else {
      this.add()
    }

    this.$nextTick(() => {
      this.form.setFieldsValue({ groupName: bag.groupName, distributeOrder: bag.distributeOrder, retailDistribution: bag.retailDistribution, names: newArr })
    })
    this.salesArea = bag.salesAreaList
    this.distributeChannel = bag.distributeChannel
    this.id = bag.id
  },
  mounted() {
    this.getAreaList()
    this.getBrandList()
  },
  methods: {
    reset() {
      this.form.resetFields()
      this.$emit('close')
    },
    select(area) {
      area.map(item => {
        if (item == 10000) {
          this.salesAreaList = [10000]
          this.ifAll = true
        } else {
          this.ifAll = false
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
    },
    remove(index) {
      let { fileds } = this
      fileds.splice(index, 1)
      this.fileds = fileds
    },
    add() {
      const obj = { name: undefined, tagItemId: '' }
      let { fileds } = this
      fileds.push(obj)
      this.fileds = fileds
    },
    async getAreaList() {
      const res = await areaList('distribute')
      if (res.code == 200) {
        this.areaList = res.data
        this.areaList.map(item => {
          this.allAreaId.push(item.id)
          this.salesArea.map(subitem => {
            if (item.name == subitem) {
              this.salesAreaList.push(item.id)
            }
          })
        })
      }
      if (this.salesAreaList.length == this.allAreaId.length) {
        this.ifAll = true
        this.salesAreaList = [10000]
      }
    },
    async getBrandList() {
      const res = await getBrandList('distribute')
      if (res.code == 200) {
        this.brandList = res.data
      }
    },
    async submit(values) {
      const disItemList = values.names
      disItemList.map(item => {
        this.brandList.map(subitem => {
          if (item.name == subitem.name) {
            item.damoHash = subitem.hash
            item.distributeId = 0
          }
        })
      })
      var params = {
        distributeOrder: values.distributeOrder,
        groupName: values.groupName,
        disItemList: disItemList,
        salesAreaList: this.ifAll ? this.allAreaId : this.salesAreaList
      }
      if (this.id) {
        params.id = this.id
      }
      // if (!params.salesAreaList.length) {
      //   this.$message.warning('请选择销售区域')
      // } else 
      if (this.distributeChannel == '达摩') {
        disItemList.map(item => {
          if (!item.name) {
            this.$message.warning('请选择品牌')
          } else if (!item.tagItemId) {
            this.$message.warning('请输入达摩标签Id')
          }
        })
        const res = await bagListUpdate('distribute', params)
        if (res.data == 'success') {
          this.$message.success('修改成功！')
          this.reset()
        } else {
          this.$message.warning(res.msg)
        }
      } else {
        const res = await bagListUpdate('distribute', params)
        if (res.data == 'success') {
          this.$message.success('修改成功！')
          this.reset()
        } else {
          this.$message.warning(res.data || res.msg)
        }
      }
    }
  }
}
</script>

<style scoped>
.ml-20 {
  margin-left: 20px;
}
.submit {
  margin-left: 8px;
  background: #409eff;
  width: 110px;
  border-radius: 10px;
  height: 40px;
  color: #fff;
  text-align: center;
  line-height: 40px;
}
.reset {
  width: 110px;
  border-radius: 10px;
  height: 40px;
  border: 1px solid #969799;
  text-align: center;
  line-height: 40px;
}
.dynamic-delete-button {
  cursor: pointer;
  position: absolute;
  right: -26px;
  top: 8px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
